package com.wuban.javaproject.request;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author:wulixin
 * @email:2765774288@qq.com
 * @desc:该类用于封装提供网络请求的功能代码，用于发起网络请求，并将 网络的数据进行返回
 * @datetime:2021/12/16 21:50
 */
public class HttpUtils {
    /**
     * 该函数用于实现get请求，并将请求的结果返回
     * @param path 请求的资源路径
     * @return 请求的结果
     */
    public static String get(String path) {
        InputStream inputStream = null;
        BufferedReader reader = null;
        InputStreamReader inputStreamReader = null;

        String line = "";//最开始空行
        String result = "";//每次读取到以后都要累计存储的结果
        try {
            //Union Resource Location 统一资源定位
            URL url = new URL(path);
            URLConnection conn = url.openConnection();
            //负责发起连接
            conn.connect();
            //字节输入流
            inputStream = conn.getInputStream();

            //字符流：按行读
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);
            //每次读一行
//            String line = reader.readLine();
//            while (line !=null){
//                reader.readLine();
//            }
            while ((line = reader.readLine()) != null) {
                result += line;
            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭读取流
            try {
                if (reader != null) {
                    reader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return result;
    }


}
